package com.atguigu.spzx.manager.service.impl.product;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.atguigu.spzx.common.exception.SpzxException;
import com.atguigu.spzx.manager.listener.CategoryExcelDataListener;
import com.atguigu.spzx.manager.mapper.product.CategoryMapper;
import com.atguigu.spzx.manager.service.product.CategoryService;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.excel.product.CategoryExcelData;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.product.CategoryVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    CategoryMapper categoryMapper;
    //分类数据变动不大：查询时 可以利用redis缓存   用户端前台系统
    @Override
    public List<Category> listCatesByPid(Long pid) {
        //1、根据pid查询分类列表
        List<Category> categories = categoryMapper.findCatesByPid(pid);
        //2、遍历所有的分类：查询它是否有下一级分类
        categories.forEach(category -> {
            int count = categoryMapper.countChildrenByPid(category.getId());
            category.setHasChildren(count>0);
        });
        return categories;
    }

    @Override
    public void export(HttpServletResponse response) {
        try {
            //查询所有分类数据 并转为excel文件需要的数据对象
            List<CategoryVo> categoryVos = categoryMapper.findAllCates().stream().map(category -> {
                CategoryVo categoryVo = new CategoryVo();
                //将category相同类型和名称的属性值 拷贝给categoryVo对象
                BeanUtils.copyProperties(category, categoryVo);
                return categoryVo;
            }).collect(Collectors.toList());
            //response配置响应头：告诉浏览器如何解析响应体内容   告诉浏览器下载附件
//            response.setHeader("content-type", MediaType.);
            //浏览器和服务器得到数据后一般会通过URLEncoder和UrlDecoder处理避免乱码
            String encode = URLEncoder.encode("商品分类", "UTF-8");
            response.setHeader("content-disposition" , "attachment;filename=_"+encode+
                    new DateTime().toString("yyyy-MM-dd")+ ExcelTypeEnum.XLSX.getValue());
            //写数据
            EasyExcel.write(response.getOutputStream()) //将数据写入到response的输出流中(响应体)
                    .sheet("分类数据")
                    .head(CategoryVo.class) //excel的表头
                    .doWrite(categoryVos); // 写入的数据集合
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.ERROR,e);
        }

    }
    //解析导入的分类的excel文件数据保存到数据库分类表中
    @Override
    public void importCates(MultipartFile file) {
        //判断文件格式是否正确
        if(file==null||
            file.isEmpty()){
            throw new SpzxException(ResultCodeEnum.ERROR,null);
        }
        if( !(   file.getOriginalFilename().toLowerCase().contains(".xls")||
                file.getOriginalFilename().toLowerCase().contains(".xlsx")||
                file.getOriginalFilename().toLowerCase().contains(".csv"))
            ){
            //文件格式错误
            throw new SpzxException(ResultCodeEnum.ERROR,null);
        }


        //1、使用easyexcel读取导入excel文件中的内容:使用课件day07资料中的 excel文件
        //为excel文件创建javabean
        //2、使用监听器解析读取到的每一行数据
        //创建监听器读取数据
        //3、保存读取到的每个分类保存到数据库中
        //在监听器的invoke方法中保存数据
        try {
            EasyExcel.read(file.getInputStream())
                    .sheet(0)
                    .head(CategoryExcelData.class)
                    .registerReadListener(new CategoryExcelDataListener(categoryMapper))
                    .doRead();
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.EXCEL_IMPORT_ERROR ,e);
        }
    }
}
